<template>
  <el-dialog
    v-model="dialog.visible"
    :title="dialog.title"
    width="70%"
    @close="cancel"
  >
    <el-form
      ref="dataFormRef"
      :model="formData"
      :rules="dataFormRules"
      :disabled="isDisabled"
      label-width="80px"
    >
      <div>
        <h3>基本信息</h3>
        <el-form-item label="活动名称" prop="name" style="width: 480px">
          <el-input
            v-model="formData.name"
            placeholder="请输入名活动名称"
            @input="onInput"
          />
        </el-form-item>

        <el-form-item label="活动时间" prop="activityTimes">
          <div class="block">
            <el-date-picker
              v-model="activityTimes"
              type="datetimerange"
              range-separator="至"
              start-placeholder="请选择"
              end-placeholder="请选择"
            />
          </div>
        </el-form-item>
      </div>

      <div>
        <h3>活动权益</h3>
        <el-form-item prop="configs">
          <el-table highlight-current-row :data="formData.configs">
            <el-table-column
              label="会员等级"
              prop="membershipLevel"
              align="center"
              width="150"
            >
              <template #default="{ row }">
                <span v-if="row.membershipLevel === 1">免费会员</span>
                <span v-if="row.membershipLevel === 2">付费会员</span>
              </template>
            </el-table-column>

            <el-table-column
              label="包邮"
              prop="freeShippingBoolean"
              align="center"
              width="150"
            >
              <template #default="{ row }">
                <el-checkbox v-model="row.freeShippingBoolean"
                  >包邮</el-checkbox
                >
              </template>
            </el-table-column>

            <el-table-column
              label="消费折扣"
              prop="point"
              align="center"
              width="100"
            >
              <template #default="{ row }">
                <el-input v-model="row.point" placeholder="请输入"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              label="送优惠券"
              prop="couponIds"
              align="center"
              width="150"
            >
              <template #default="{ row }">
                <el-button
                  v-hasPerm="['act:festival:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="chooseCoupon(row.membershipLevel)"
                  >设置优惠券</el-button
                >
              </template>
            </el-table-column>

            <el-table-column
              label="状态"
              prop="status"
              align="center"
              width="150"
            >
              <template #default="{ row }">
                <span>{{ row.status ? "已开启" : "已关闭" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="150"
            >
              <template #default="{ row }">
                <el-button
                  v-hasPerm="['act:festival:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="switchSwitch(row)"
                >
                  {{ row.status ? "关闭" : "启用" }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>

      <el-form-item label="发放时间" prop="distributionTime">
        <el-select v-model="beforeDays" placeholder="请选择" class="spacing">
          <el-option
            v-for="item in beforeDaysOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          >
          </el-option>
        </el-select>

        <el-select v-model="beforeHours" placeholder="请选择">
          <el-option
            v-for="item in timeOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmission">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <couponDailog ref="chooseCouponRef" @confirm="updateChooseCouponIds" />
</template>

<script setup lang="ts">
defineOptions({
  name: "AddOrEditHolidayActivity",
  inheritAttrs: false,
});

defineExpose({
  openAddDialog,
  openEditDialog,
});

import { FestivalTypeForm } from "@/api/marketing/types";
import {
  addFestableActivity,
  getActivityInfoById,
  updateFestableActivity,
  // getCouponList,
} from "@/api/marketing/index";
import { formatDate } from "@/utils/dateUtils";
import couponDailog from "@/views/marketing/holiday-marketing/coupon-dailog.vue";
import { getCurrentInstance } from "vue"; // 先引入

const emit = defineEmits(["confirm"]);

const chooseCouponRef = ref();
const dataFormRef = ref(ElForm);
let isDisabled = ref<boolean>(false);

const dialog = reactive<DialogOption>({
  title: "新增活动",
  visible: false,
});

let formData = reactive<FestivalTypeForm>({
  id: undefined,
  name: "",
  startTime: "",
  endTime: "",
  distributionTime: "",
  configs: [
    {
      membershipLevel: 1,
      freeShipping: 0,
      freeShippingBoolean: false,
      point: 0,
      status: 1,
      couponIds: [],
    },
    {
      membershipLevel: 2,
      freeShipping: 0,
      freeShippingBoolean: false,
      point: 0,
      status: 0,
      couponIds: [],
    },
  ],
});

let activityTimes = ref<[Date | undefined, Date | undefined]>();
//发放时间
//前 ? 天
let beforeDays = ref<number>(0);
//具体时间
let beforeHours = ref<number>(0);

//自定义校验规则
const validateActivityTimes = (rule: any, value: any, callback: any) => {
  let startDate = activityTimes.value?.[0];
  if (startDate) {
    let valid =
      parseInt(String(startDate.getTime() - new Date().getTime())) >=
      60 * 10 * 1000;
    if (!valid) {
      callback(new Error("开始时间 - 当前时间, 必须大于等于10分钟!"));
    }

    callback();
  } else {
    callback(new Error("请选择活动时间!"));
  }
};

const validateDistributionTime = (rule: any, value: any, callback: any) => {
  if (beforeDays.value >= 0 && beforeHours.value >= 0) {
    let startDate = activityTimes.value?.[0];
    if (!startDate) {
      callback();
    }

    let totalHours = beforeDays.value * 24 + beforeHours.value;
    let valid =
      parseInt(String(startDate!.getTime() - new Date().getTime())) >=
      totalHours * 60 * 60 * 1000;
    if (!valid) {
      callback(new Error("开始时间 - 当前时间 必须大于 发放时间 !"));
    }

    callback();
  } else {
    callback(new Error("请选择发放时间!"));
  }
};

const dataFormRules = reactive({
  name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
  activityTimes: [
    { required: true, validator: validateActivityTimes, trigger: "blur" },
  ],
  distributionTime: [
    { required: true, validator: validateDistributionTime, trigger: "blur" },
  ],
});

const { ctx: that }: any = getCurrentInstance();

function onInput() {
  //在Vue官方文档中指出，$forceUpdate具有强制刷新的作用，迫使vue实例重新（rander）渲染虚拟dom
  console.log(that);

  // that.$forceUpdate(); //也没效果
}

// 新增
function openAddDialog() {
  dialog.title = "新增活动";
  //初始化发放时间的选项
  beforeDaysOptions.value = processingOption();
  timeOptions.value = fackTimes();
  isDisabled.value = false;
  dialog.visible = true;
}

function openEditDialog(id: number, isDisable: boolean) {
  dialog.title = "编辑活动";

  //初始化发放时间的选项
  beforeDaysOptions.value = processingOption();
  timeOptions.value = fackTimes();
  isDisabled.value = isDisable;

  getActivityInfoById(id).then(({ data }) => {
    // console.log(data);
    // formData = data; //会导致input输入不立刻生效
    Object.assign(formData, data);

    //回显日期选择
    activityTimes.value = [
      new Date(formData.startTime),
      new Date(formData.endTime),
    ];

    //回显是否包邮
    //在 el-checkbox 元素中定义 v-model 绑定变量，单一的 checkbox 中，默认绑定变量的值会是 Boolean，选中为 true, 但后端返回的是 number 类型
    formData.configs?.forEach((config) => {
      config.freeShippingBoolean = config.freeShipping == 1;
    });

    //回显前几天， 几小时
    let intervalSeconds = parseInt(
      String(
        new Date(formData.startTime).getTime() / 1000 -
          new Date(formData.distributionTime).getTime() / 1000
      )
    );
    let days = parseInt(String(intervalSeconds / (60 * 60 * 24)));
    // let beforeHours = intervalMillSeconds / ( 60 * 60 ) - ( 24 * days );
    let hours = parseInt(String((intervalSeconds / (60 * 60)) % 24));

    beforeDays.value = days;
    beforeHours.value = hours;

    dialog.visible = true;
  });
}

const timeOptions = ref<OptionType[]>();
function fackTimes(): OptionType[] {
  let times: OptionType[] = [];
  for (let index = 0; index < 24; index++) {
    //补0
    const timeStr = index < 10 ? "0" + index + ":00" : index + ":00";
    times.push({ label: timeStr, value: index });
  }
  return times;
}

const beforeDaysOptions = ref<OptionType[]>();
function processingOption(): OptionType[] {
  let option: OptionType[] = [];
  for (let i = 0; i <= 7; i++) {
    option.push({ label: "前" + i + "天", value: i });
  }
  return option;
}

function switchSwitch(row: any) {
  row.status = row.status ? 0 : 1;
}

//选择优惠券
function chooseCoupon(membershipLevel: number) {
  let couponIds: number[] = [];
  formData.configs?.forEach((item) => {
    if (item.membershipLevel == membershipLevel)
      couponIds = [...item.couponIds];
  });
  chooseCouponRef.value.open(membershipLevel, couponIds);
}

function updateChooseCouponIds(membershipLevel: number, couponIds: number[]) {
  formData.configs?.forEach((item) => {
    if (item.membershipLevel == membershipLevel) item.couponIds = couponIds;
  });
}
function cancel() {
  resetForm();
  dialog.visible = false;
}

//确定
function handleSubmission() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      //在 el-checkbox 元素中定义 v-model 绑定变量，单一的 checkbox 中，默认绑定变量的值会是 Boolean，选中为 true, 但后端要求传 number 类型
      formData.configs?.forEach((config) => {
        config.freeShipping = config.freeShippingBoolean ? 1 : 0;
      });

      formData.startTime = formatDate(
        activityTimes.value?.[0],
        "YYYY-mm-dd HH:MM:SS"
      );

      formData.endTime = formatDate(
        activityTimes.value?.[1],
        "YYYY-mm-dd HH:MM:SS"
      );

      // 选中n天 beforeDays.value
      const choseTime: number = beforeDays.value!; //前n天
      // 选中n小时 beforeHours.value
      const chooseHours: number = beforeHours.value!;

      //开始时间
      const startDate = new Date(formData.startTime);
      //过去时间 = startTime - 前n天 - n小时
      const pastTime = new Date(
        startDate.getTime() -
          3600 * 1000 * 24 * choseTime -
          3600 * 1000 * chooseHours
      );
      formData.distributionTime = formatDate(pastTime, "YYYY-mm-dd HH:MM:SS");
      // console.log(formData.distributionTime); //2023-08-09 23:00:00
      if (formData.id) {
        updateFestableActivity(formData).then(() => {
          ElMessage.success("修改成功");
          resetForm();
          dialog.visible = false;
          emit("confirm");
        });
      } else {
        addFestableActivity(formData).then(() => {
          ElMessage.success("新增成功");
          resetForm();
          dialog.visible = false;
          emit("confirm");
        });
      }
    }
  });
}

/** 重置表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;

  Object.assign(formData, {
    id: undefined,
    name: "",
    startTime: "",
    endTime: "",
    distributionTime: "",
    configs: [
      {
        membershipLevel: 1,
        freeShipping: 0,
        freeShippingBoolean: false,
        point: 0,
        status: 1,
        couponIds: [],
      },
      {
        membershipLevel: 2,
        freeShipping: 0,
        freeShippingBoolean: false,
        point: 0,
        status: 0,
        couponIds: [],
      },
    ],
  });

  activityTimes.value = [undefined, undefined];
  beforeDays.value = 0;
  beforeHours.value = 0;
}
</script>

<style lang="scss" scoped>
h3 {
  font-size: 15px;
}

.spacing {
  margin: 0 10px;
}
</style>
